<template>
	<!-- #ifdef MP-WEIXIN -->
	<page-meta :page-style="pageStyle" />
	<!-- #endif -->
	<view class="profit">
		<view class="tip">
			<view>
				<image src="https://julimeng-prod.oss-cn-hangzhou.aliyuncs.com/managehub/MP/activity/tip.png"></image>
				<text>提现前需添加官网微信</text>
			</view>
			<text class="tip-link" @click="handleAdd">添加官网微信</text>
		</view>
		<view class="amount">
			<view class="amount-main">
				<view v-for="(aItm, key) in amountMap" :key="key" class="amount-item">
					<view>{{ aItm.label }}</view>
					<view class="amount-val">{{ aItm.val }}</view>
				</view>
			</view>
			<view class="amount-btn" :class="{
				disabled: !grable || disableGrab
			}" @click="handleGrab">提现</view>
			<view class="amount-tip">
				<text v-if="grable">每日最多可提现1次，单次提现金额不得低于0.3元，本次活动采用“一人一证”实名参与机制（微信官方要求）</text>
				<text v-else>现金奖励活动已结束，目前暂不支持提现哦。</text>
			</view>
		</view>
		<view v-for="(record, key) in recordMap" :key="key" class="record" :class="{
			mr: key === 'reward'
		}">
			<view class="record-wrap">
				<view class="record-title">我的{{ record.label }}</view>
				<scroll-view scroll-y style="height: 516rpx;" @scrolltolower="handlePage(key)">
					<view v-if="key === 'grab' && refreshing" class="refresh">
						<!-- <view class="refresh-icon"> -->
						<uni-icons class="refresh-icon" type="spinner-cycle" color="#FFBA9B" size="50" />
						<!-- </view> -->
						<view>数据加载中...</view>
					</view>
					<template v-else-if="key === 'reward' || !refreshing">
						<view v-for="(rItm, ri) in record.list" :key="key + '-' + ri" class="record-item">
							<view class="record-name">
								<view class="wrap">
									<text>{{ rItm.name }}</text>
									<view v-if="rItm.refuse" class="icon" @click="() => handleShowReason(rItm.id)">
										<uni-icons type="info-filled" size="20" color="#FF634B" />
									</view>
									<view v-if="showReason && reasonId === rItm.id" class="reason">
										{{ rItm.reason || '' }}
									</view>
								</view>

							</view>
							<view class="record-time">{{ rItm.time }}</view>
							<view class="record-num">{{ rItm.amount }}元</view>
							<view v-if="rItm.grable" class="record-grab" @click="$event => handleDraw(rItm)">领取</view>
						</view>
					</template>
					<view v-if="!record.list || !record.list.length" class="record-empty">
						<image mode="heightFix"
							src="https://julimeng-prod.oss-cn-hangzhou.aliyuncs.com/managehub/MP/activity/empty.png">
						</image>
						<view class="record-emptxt">{{ record.empTxt }}</view>
						<view class="record-btn" @click="$event => handleGo(key)">{{ record.opTxt }}</view>
					</view>
				</scroll-view>
			</view>
		</view>

		<view v-if="showReason" class="mask" @click="handleCloseReason" />

		<view v-if="showHb" class="activity mask">
			<image src="https://julimeng-prod.oss-cn-hangzhou.aliyuncs.com/managehub/MP/activity/bg.png"
				class="activity-bg" mode="widthFix"></image>
			<view @click="() => handleDraw(hbInfo)">
				<image src="https://julimeng-prod.oss-cn-hangzhou.aliyuncs.com/managehub/MP/activity/hb.png"
					class="activity-img" mode="widthFix" />
			</view>
			<view class="activity-amount">¥ {{ hbInfo.price || '' }}</view>
		</view>
	</view>
</template>

<script>
	import {
		getAccountApi,
		getGrabApi,
		getRewardApi,
		recordGrabApi,
		getGrabDetailApi,
		checkGrableApi
	} from '@/api/activity'
	import {
		mapGetters
	} from 'vuex'
	import {
		APP_ID,
		H5_APP_ID
	} from '@/config/app.js'
	import {
		openGrabSubscribe
	} from "@/utils/SubscribeMessage";
	import {
		shareToFriend
	} from "@/api/share";
	import LockScrollMixin from '@/mixins/lockScroll.js'
	// #ifdef H5
	import wx from "@/js_sdk/jweixin-module";
	import app from '../../store/modules/app';
	// #endif

	export default {
		mixins: [LockScrollMixin],
		data() {
			return {
				amountMap: {
					balance: {
						label: '账户余额',
						val: '0.00'
					},
					grab: {
						label: '提现中金额',
						val: '0.00'
					},
					getted: {
						label: '已提现金额',
						val: '0.00'
					}
				},

				recordMap: {
					reward: {
						label: '奖励记录',
						pageNum: 1,
						pageTotal: 0,
						empTxt: '暂无奖励，快去查询企业获取奖励',
						opTxt: '去查询',
						list: []
					},
					grab: {
						label: '提现记录',
						pageNum: 1,
						pageTotal: 0,
						empTxt: '暂无提现记录，快去提现吧',
						opTxt: '去提现',
						list: []
					},
				},
				showReason: false,
				reasonId: '-1',
				showHb: false,
				hbInfo: {},
				grable: true,
				refreshing: false
			}
		},
		computed: {
			...mapGetters(['userInfo']),
			disableGrab() {
				const money = +this.amountMap.balance.val
				const grabMoney = isNaN(money) ? 0 : money
				return grabMoney < 0.3
			}
		},
		methods: {
			// 无数据去跳转
			handleGo(key) {
				if (key === 'grab') {
					uni.pageScrollTo({
						scrollTop: 0
					})
				} else {
					uni.navigateTo({
						url: `/pagesWater/taxSearch/index`
					})
				}
			},
			// 展示拒绝原因
			handleShowReason(id) {
				this.showReason = true
				this.reasonId = id
				this.$store.commit('SET_SCROLL_LOCK', true)
			},
			// 关闭拒绝原因展示
			handleCloseReason() {
				this.showReason = false
				this.$store.commit('SET_SCROLL_LOCK', false)
			},
			// 添加企业微信
			handleAdd() {
				// #ifdef MP-WEIXIN
				wx.openCustomerServiceChat({
					extInfo: {
						url: 'https://work.weixin.qq.com/kfid/kfc389dffe7ae981936'
					},
					corpId: 'ww1c4069be6ea4025e',
					showMessageCard: true,
					success(res) {
						console.log(res);
					},
					fail(err) {
						console.log(err);
					},
				})
				// #endif

				// #ifdef H5
				location.href = 'https://work.weixin.qq.com/kfid/kfc389dffe7ae981936';
				// #endif
			},
			// 账户
			async getAccount(isRefresh) {
				console.log('刷新账户信息。。。。。', isRefresh)
				const res = await getAccountApi()
				const {
					balance = 0, inWithdrawal = 0, endWithdrawal = 0
				} = res?.data || {}
				this.$set(this.amountMap.balance, 'val', (balance / 100).toFixed(2))
				this.$set(this.amountMap.grab, 'val', (inWithdrawal / 100).toFixed(2))
				this.$set(this.amountMap.getted, 'val', (endWithdrawal / 100).toFixed(2))
			},
			// 提现记录
			async getGrabList() {
				const {
					list: originList = [],
					pageNum = 1
				} = this.recordMap.grab
				const res = await getGrabApi({
					pageNum,
					pageSize: 10
				})
				const {
					list = [], totalPage = 0
				} = res.data || {}
				this.$set(this.recordMap, 'grab', {
					...this.recordMap.grab,
					list: originList.concat(list.map(item => {
						return {
							time: item.createTime,
							name: item.statusName,
							amount: ((item.price ?? 0) / 100).toFixed(2),
							refuse: +item.status === 20,
							grable: +item.status === 10,
							pkg: item.transferChannelPackageInfo,
							mchId: item.transferChannelMchId,
							trsId: item.payTransferId,
							reason: item.auditReason,
							id: item.id
						}
					})),
					pageTotal: totalPage
				})
			},
			// 奖励记录
			async getRewardList() {
				const {
					list: originList = [],
					pageNum = 1
				} = this.recordMap.reward
				const res = await getRewardApi({
					pageNum,
					pageSize: 10
				})
				const {
					list = [], totalPage = 0
				} = res?.data || {}
				this.$set(this.recordMap, 'reward', {
					...this.recordMap.reward,
					list: originList.concat(list.map(item => {
						return {
							time: item.createTime,
							name: item.title,
							amount: ((item.price ?? 0) / 100).toFixed(2),
						}
					})),
					pageTotal: totalPage
				})
			},
			// 分页
			handlePage(key) {
				const {
					pageNum,
					pageTotal
				} = this.recordMap[key]
				if (pageNum < pageTotal) {
					this.$set(this.recordMap, key, {
						...this.recordMap[key],
						pageNum: pageNum + 1
					})
					key === 'reward' ? this.getRewardList() : this.getGrabList()
				}
			},
			// 提现(提交审核)
			handleGrab() {
				if (!this.grable || this.disableGrab) return
				const amount = this.amountMap.balance.val
				// #ifdef MP-WEIXIN 
				openGrabSubscribe().then(() => {
					uni.navigateTo({
						url: `/pagesUser/withDrawal/index?priceNum=${amount}`
					})
				})
				// #endif

				// #ifdef H5
				uni.navigateTo({
					url: `/pagesUser/withDrawal/index?priceNum=${amount}`
				})
				// #endif
			},
			// 领取成功处理
			handleDrawSuccess() {
				this.$util.Tips('领取成功')
				this.updateInfo(trsId)
				this.showHb = false
				this.$store.commit('SET_SCROLL_LOCK', false)
			},
			// 领取（领取到零钱）
			async handleDraw({
				pkg,
				mchId,
				trsId
			}) {
				if (!pkg || !mchId) {
					return this.$util.Tips('无商户信息')
				}
				// #ifdef MP-WEIXIN 
				uni.requestMerchantTransfer({
					package: pkg,
					mchId,
					appId: APP_ID,
					success: () => {
						this.handleDrawSuccess(trsId)
					},
					fail: err => {
						console.log(err)
						if (err.errMsg == "requestMerchantTransfer:fail cancel") {
							return this.$util.Tips('您取消了领取')
						}
						this.$util.Tips('领取失败')
					}
				})
				// #endif

				// #ifdef H5
				const params = {
					url: encodeURIComponent(window.location.href.split("#")[0]),
				};
				const res = await shareToFriend(params);
				const {
					appId,
					timestamp,
					nonceStr,
					signature
				} = res?.data || {}
				try {
					console.log('h5收款的appID ', H5_APP_ID)
					wx.config({
						debug: false, // 开启调试模式
						appId: H5_APP_ID, // 必填，公众号的唯一标识
						timestamp, // 必填，生成签名的时间戳
						nonceStr, // 必填，生成签名的随机串
						signature, // 必填，签名
						jsApiList: [
							"requestMerchantTransfer",
						], // 必填，需要使用的JS接口列表
					});
					wx.ready(() => {
						wx.checkJsApi({
							jsApiList: [
								"requestMerchantTransfer",
							],
							success: res => {
								if (res.checkResult['requestMerchantTransfer']) {
									WeixinJSBridge.invoke('requestMerchantTransfer', {
											mchId,
											appId: H5_APP_ID,
											package: pkg,
										},
										({
											err_msg
										}) => {
											console.log(' transfer  ', res)
											if (err_msg === 'requestMerchantTransfer:ok') {
												uni.setStorageSync('ACTIVITY_DRAW', trsId)
												console.info('展示首款页面成功')
											} else if (err_msg ===
												'requestMerchantTransfer:cancel') {
												return this.$util.Tips('您取消了领取')
											} else if (err_msg ===
												'requestMerchantTransfer:fail') {
												return this.$util.Tips('领取失败')
											}
										}
									);
								} else {
									uni.showModal({
										content: '请更新微信至最新版本。',
										showCancel: false,
									});
								}
							},
						})
					})
				} catch (err) {
					console.log(err)
				}
				// #endif
			},
			// 领取后刷新
			async updateInfo(id) {
				console.log('update.........')
				this.refreshing = true
				this.$set(this.recordMap, 'grab', {
					...this.recordMap.grab,
					pageNum: 1,
					pageTotal: 0,
					list: []
				})
				try {
					console.log('更新状态了', id)
					id && await recordGrabApi(id)
					setTimeout(async () => {
						console.log('领取状态已更新。。。。刷新了')
						await this.getGrabList()
						this.getAccount(true)
						this.refreshing = false
					}, id ? (3 + Math.random() * 2) * 1000 : 0);
				} catch {
					this.refreshing = false
				}
			},
			// 查询提现记录详情
			async getGradDetail(id) {
				const res = await getGrabDetailApi(id)
				const {
					status,
					price,
					transferChannelPackageInfo: pkg,
					transferChannelMchId: mchId,
					payTransferId: trsId
				} = res?.data || {}
				this.showHb = status === 10 && !isNaN(+price) && +price > 0 // 审批通过 可领取到零钱
				if (this.showHb) {
					this.hbInfo = {
						price: (+price / 100).toFixed(2),
						pkg,
						mchId,
						trsId
					}
				} else {
					this.hbInfo = {}
				}
				this.$store.commit('SET_SCROLL_LOCK', !!this.showHb)
			},
			async checkGrable() {
				const res = await checkGrableApi()
				this.grable = res?.data === true
			}
		},
		mounted() {
			this.getAccount()
			this.getGrabList()
			this.getRewardList()
			this.checkGrable()
		},
		onShow() {
			const trsId = uni.getStorageSync('ACTIVITY_DRAW')
			trsId && this.handleDrawSuccess(trsId)
		},
		onLoad({
			id,
			from
		}) {
			console.log('Profit load load load....................', from === 'share')
			console.log('id.   从消息通知进入。。。', id)
			id && this.getGradDetail(id) // 从提现消息通知进入
			uni.$on('ACTIVITY_GRAB_REFRESH', () => {
				this.updateInfo()
			})
		},
		onUnload() {
			uni.$off('ACTIVITY_GRAB_REFRESH')
			uni.removeStorageSync('ACTIVITY_DRAW')
		},
		// // #ifdef MP-WEIXIN
		// onShareAppMessage: function(res) {
		// 	return {
		// 		imageUrl: 'https://julimeng-prod.oss-cn-hangzhou.aliyuncs.com/managehub/MP/activity/invite.png',
		// 		title: '注册领现金红包',
		// 		path: '/pagesUser/activity/profit?id='+ Date.now() + '&from=share'
		// 	}
		// },
		// // #endif
	}
</script>

<style lang="scss" scoped>
	.profit {
		min-height: 100vh;
		background: #FEEBCA;

		.mask {
			position: fixed;
			left: 0;
			right: 0;
			top: 0;
			bottom: 0;
			z-index: 999;
			background-color: rgba(#000, 0.6);
		}

		.activity {

			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: column;

			&-amount {
				position: fixed;
				top: 50%;
				font-size: 80rpx;
				color: #F60420;
				z-index: 999;
				left: 50%;
				font-weight: bold;
				transform: translate(-50%, -30rpx);
			}

			&-img {
				position: relative;
				z-index: 10;
				width: 688rpx;
				margin-top: -50rpx;
			}

			&-bg {
				position: absolute;
				width: 750rpx;
				left: 0;
				top: 50%;
				transform: translateY(calc(-50% - 24px));
				z-index: 1;
			}

		}

		.refresh {
			height: 100%;
			display: flex;
			flex-direction: column;
			line-height: 60rpx;
			font-size: 26rpx;
			justify-content: center;
			align-items: center;
			color: #937371;

			@keyframes rotate {
				from {
					transform: rotate(0deg);
				}

				to {
					transform: rotate(360deg);
				}
			}

			&-icon {
				animation: rotate 1s linear infinite;
				width: 50px;
				height: 50px;
				line-height: 50px;
			}
		}

		.record {
			padding: 0 26rpx 55rpx;

			&-grab {
				background: linear-gradient(to bottom, #FECC7E, #FF5F48);
				color: #fff;
				line-height: 50rpx;
				height: 50rpx;
				padding: 0 30rpx;
				border-radius: 30rpx;
				position: absolute;
				right: 56rpx;
				top: 66rpx;

			}

			&.mr {
				padding-top: 37rpx;
			}

			&-wrap {
				box-sizing: content-box;
				background-color: #FFF6DD;
				border: 8rpx solid #FFDEC6;
				height: 600rpx;
				border-radius: 30rpx;
			}

			&-title {
				font-size: 34rpx;
				height: 100rpx;
				text-align: center;
				color: #830D06;
				font-weight: bold;
				background-image: url('https://julimeng-prod.oss-cn-hangzhou.aliyuncs.com/managehub/MP/activity/record-bg.png');
				background-size: 417rpx 71rpx;
				background-repeat: no-repeat;
				background-position: 132.5rpx 0;
				position: relative;
				z-index: 3;
				margin-top: -16rpx;
				padding-top: 10rpx;
			}

			&-item {
				position: relative;
				padding: 30rpx 60rpx;

				&::after {
					position: absolute;
					content: '';
					bottom: 0;
					left: 60rpx;
					right: 60rpx;
					height: 1rpx;
					background-color: #FFDEC6;
				}
			}

			&-name,
			&-num {
				font-size: 30rpx;
				color: #830D06;
				line-height: 28rpx;
			}

			&-name {
				.icon {
					transform: rotate(180deg);
					display: inline-block;
					margin-left: 6rpx;
				}


				.wrap {
					position: relative;

					.reason {
						position: absolute;
						background-color: #fff;
						z-index: 1000;
						color: #333;
						max-width: 500rpx;
						min-width: 6em;
						border-radius: 12rpx;
						padding: 30rpx;
						left: 0;
						top: 55rpx;
						box-sizing: border-box;


						&::before {
							position: absolute;
							content: '';
							border: 30rpx solid #fff;
							top: -45rpx;
							left: 135rpx;
							border-color: transparent transparent #fff transparent;
						}
					}
				}
			}

			&-time {
				font-size: 24rpx;
				line-height: 24rpx;
				margin-top: 20rpx;
				color: #AC8E88;
			}

			&-num {
				position: absolute;
				right: 60rpx;
				top: 30rpx;
			}

			&-btn {
				width: 250rpx;
				height: 88rpx;
				background: linear-gradient(#FECC7E 0%, #FFA86A 15%, #FF5D48 100%);
				border-radius: 44rpx;
				font-weight: 600;
				font-size: 34rpx;
				color: #FFFFFF;
				text-align: center;
				line-height: 88rpx;
				margin: 0 auto;
				margin-top: 20rpx;
			}

			&-empty {
				text-align: center;
				padding-top: 74rpx;

				image {
					height: 185rpx;
					width: 339rpx;
				}
			}

			&-emptxt {
				font-size: 30rpx;
				color: #937371;
			}
		}

		.tip {
			height: 68rpx;
			border-top: 8rpx solid #FFDFC6;
			background-color: #FFEEEB;
			font-size: 26rpx;
			color: #666;
			line-height: 68rpx;
			display: flex;
			justify-content: space-between;
			padding: 0 30rpx;
			box-sizing: content-box;

			&-link {
				color: #FF634B;
			}

			image {
				width: 23rpx;
				height: 22rpx;
				margin-right: 10rpx;
			}
		}

		.amount {
			padding: 60rpx 30rpx 30rpx;
			border-bottom: 8rpx solid #FFDFC6;
			background-color: #FFF6DD;

			&-main {
				display: flex;
				justify-content: space-between;
			}

			&-item {
				text-align: center;
				font-size: 36rpx;
				color: #333;
				font-weight: bold;
				line-height: 36rpx;
			}

			&-val {
				color: #666;
				font-size: 28rpx;
				margin-top: 20rpx;
				line-height: 28rpx;
			}

			&-btn {
				margin: 66rpx auto 36rpx;
				width: 300rpx;
				height: 88rpx;
				border-radius: 10rpx;
				background-color: #FF634B;
				font-size: 36rpx;
				font-weight: bold;
				text-align: center;
				line-height: 88rpx;
				color: #fff;

				&.disabled {
					background-color: #ddd;
				}
			}

			&-tip {
				color: #666;
				font-size: 26rpx;
				line-height: 28rpx;
				text-align: center;

				text {
					text-align: left;
					display: inline-block;
				}
			}
		}
	}
</style>